package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author zmc
 * @date 2025-10-10
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;
    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn)?1:0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public int apply(CheckInApplyDto dto) {
        //查询四个表
        CheckInConfigDto configDto = dto.getCheckInConfigDto();
        CheckInElderDto elderDto = dto.getCheckInElderDto();
        CheckInContractDto contractDto = dto.getCheckInContractDto();
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        //查询老人表
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,elderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus,4);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(elder!=null){
            throw new BaseException("该老人已入住");
        }
        //更新床位的状态
        Long bedId = configDto.getBedId();
        Bed bed = bedMapper.selectById(bedId);
        if(bed==null){
            throw new BaseException("请选择正确的床位");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //新增或更新老人
        elder = saveOrUpdateElder(elderDto,bed);

        saveContract(contractDto,elder,configDto);

        //新增入住信息
        CheckIn checkIn = saveCheckIn(elder,configDto,elderFamilyDtoList);

        //新增入住配置
        saveCheckInConfig(contractDto,elder,configDto,checkIn);

        return 1;
    }

    @Override
    public CheckInDetailVo detail(Integer id) {

        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询checkin id
        CheckIn checkIn =getById(id);
        long elderId = checkIn.getElderId();

        //查询老人信息  老人身份证号
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,checkIn.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
//        checkInElderVo.setId(elder.getBedId());
//        checkInElderVo.setName(elder.getName());
//        checkInElderVo.setIdCardNo(elder.getIdCardNo());
//        checkInElderVo.setBirthday(elder.getBirthday());
//        checkInElderVo.setSex(elder.getSex());
//        checkInElderVo.setPhone(elder.getPhone());
//        checkInElderVo.setAddress(elder.getAddress());
//        checkInElderVo.setImage(elder.getImage());
//        checkInElderVo.setIdCardNationalEmblemImg(elder.getIdCardNationalEmblemImg());
//        checkInElderVo.setIdCardPortraitImg(elder.getIdCardPortraitImg());
//        checkInElderVo.setAge(DateUtil.ageOfNow(elder.getBirthday()));
        BeanUtils.copyProperties(elder,checkInElderVo);
        //计算年龄
        int age = DateUtil.ageOfNow(elder.getBirthday());
        checkInElderVo.setAge(age);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //根据老人id获取合同信息
        LambdaQueryWrapper<Contract> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Contract::getElderId,elderId);
        Contract contract = contractMapper.selectOne(queryWrapper2);
        checkInDetailVo.setContract(contract);
        //获取家庭信息
        String remark= checkIn.getRemark();
        //JSON转list
        List<ElderFamilyVo>list = JSONUtil.toList(remark,ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(list);
        //获取配置信息
        LambdaQueryWrapper<CheckInConfig> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper3);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);

        //日期，床位
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());


        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        return checkInDetailVo;
    }


    private void saveCheckInConfig(CheckInContractDto contractDto, Elder elder, CheckInConfigDto configDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();

        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setNursingLevelId(configDto.getNursingLevelId());
        checkInConfig.setNursingLevelName(configDto.getNursingLevelName());
        checkInConfig.setFeeStartDate(configDto.getFeeStartDate());
        checkInConfig.setFeeEndDate(configDto.getFeeEndDate());
        checkInConfig.setDeposit(configDto.getDeposit());
        checkInConfig.setNursingFee(configDto.getNursingFee());
        checkInConfig.setBedFee(configDto.getBedFee());
        checkInConfig.setInsurancePayment(configDto.getInsurancePayment());
        checkInConfig.setGovernmentSubsidy(configDto.getGovernmentSubsidy());
        checkInConfig.setOtherFees(configDto.getOtherFees());

        checkInConfigMapper.insert(checkInConfig);

    }

    private CheckIn saveCheckIn(Elder elder, CheckInConfigDto configDto,List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();

        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(configDto.getStartDate());
        checkIn.setEndDate(configDto.getEndDate());
        checkIn.setNursingLevelName(configDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);

        // 把家属信息转成json字符串
        String jsonStr = JSONUtil.toJsonStr(elderFamilyDtoList);
        checkIn.setRemark(jsonStr);

        checkInMapper.insert(checkIn);



        return checkIn;

    }

    private void saveContract(CheckInContractDto contractDto,Elder elder,CheckInConfigDto configDto) {
        Contract contract = new Contract();

        contract.setElderId(elder.getId());
        contract.setContractName(contractDto.getContractName());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setAgreementPath(contractDto.getAgreementPath());
        contract.setThirdPartyPhone(contractDto.getThirdPartyPhone());
        contract.setThirdPartyName(contractDto.getThirdPartyName());
        contract.setElderName(elder.getName());
        contract.setStartDate(configDto.getStartDate());
        contract.setEndDate(configDto.getEndDate());
        contract.setStatus(1);
        contract.setSignDate(contractDto.getSignDate());

        contractMapper.insert(contract);

    }

    //新增或更新老人
    private Elder saveOrUpdateElder(CheckInElderDto elderDto,Bed bed) {
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,elderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(elder==null){
            elder = new Elder();
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(4);
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.insert(elder);
        }else{
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(4);
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.updateById(elder);
        }

        return elder;

    }

}
